<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class OrderModel{ 
    protected $CI;
    private $pageSize = 10;
    public function __construct(){
        $this->CI =& get_instance();
        $this->CI->load->database();
    }
    

    /**
     * [createOrder description]
     * @param  [type] $userId [description]
     * @param  [type] $data   [description]
     * @return [type]         [description]
     */
    public function createOrder($userId,$data){
        $this->CI->db->trans_start();
        // 1更改任务状态
        $taskId = $data['id'];
        $status = $this->CI->db->set("status",-2)->where("id",$data['id'])->update('task');
        if(!$status){
            $this->CI->db->trans_rollback();
            return ['status'=>3004];
        }
        if(!$data['orderAmount']){
            $data['orderAmount'] = 0.01;//最少支付1分钱
        }
        // 2生成待支付订单
        $temp = array(
            "user_id"=>$userId,
            "order_number"=>$data['orderNumber'],
            "release_id"=>$data['id'],
            "order_type"=>$data['orderType'],
            "order_amount"=>$data['orderAmount'],
            "create_month" => date("Y-m"),
            "deadline"=>date("Y-m-d H:i:s",strtotime("+10 minute")), //10分钟之内要支付
        );
        $status = $this->CI->db->insert('user_order', $temp);
        if(!$status){
            $this->CI->db->trans_rollback();
            return ['status'=>3004];
        }
        // 3调用微信接口生成订单
        $timeNow = date("Y-m-d H:i:s");
        // 3.1 查询是否绑定了微信 
        $this->CI->load->library('Wxpay/wxpay'); //公共 
        $nofityUrl = $data['baseUrl'] . '/index.php/order/notifyOrder';             
        $body = "缴纳保证金";
        $payInfo = $this->CI->wxpay->wxpay($data['orderNumber'],$data['orderAmount'],$nofityUrl,$data['openId'],$body);
       // var_dump($payInfo);exit;
        $ret['status'] = 0;
        $ret['payInfo'] = $payInfo;
        $this->CI->db->trans_complete();
        return $ret;
    }



    /**
     * [unPayOrder 是否有尚未支付的订单]
     * @param  [type] $status [description]
     * @return [type]       [description]
     */
    public function unPayedOrder($userId){
        $fileterArray['user_id'] = $userId;
        $fileterArray['status'] = 0;
        $totalQuery = $this->CI->db->select("count(id) as totalcount")
                ->get_where('user_order', $fileterArray, 1, 0);
        $totalResult = $totalQuery->row();
        return isset($totalResult->totalcount)?$totalResult->totalcount:0;
    }  



    /**
     * [adminUnLockOrder description]
     * @return [type] [description]
     */
    public function adminUnLockOrder(){
        $timenow = date("Y-m-d H:i:s");
        $query = "SELECT user_order.id 
                ,user_order.release_id
                FROM user_order
                join task on user_order.release_id = task.id 
                where user_order.deadline<'$timenow' and user_order.status = 0
                and task.status=-2";
                // echo $query;exit;
        $info = $this->CI->db->query($query);
        foreach ($info->result() as $key => $value) {
            $taskId = $value->release_id;
            //跟新任务
            $status = $this->CI->db->set("status",0)->where("id",$taskId)->update('task');
            
            $orderId = $value->id;
            //更新订单状态
            $status = $this->CI->db->set("status",2)->where("id",$orderId)->update('user_order');
        }
        return 0;
    }

    /**
     * [adminUnLockOrder description]
     * @return [type] [description]
     */
    public function orderDetail($userId,$orderNumber){
        $column = "id,user_id as userId
                ,order_number as orderNumber
                ,order_amount as orderAmount
                ,create_time as createTime
                ,pay_time as payTime
                ,status";
        $info = $this->CI->db->select($column)->get_where('user_order', array('order_number' => $orderNumber), 1, 0);
        return $info->row();
    }  

    /**
     * [orderDetailByReleaseId description]
     * @return [type] [description]
     */
    public function orderDetailByReleaseId($userId,$releaseId){
        $column = "id,user_id as userId
                ,order_number as orderNumber
                ,order_amount as orderAmount
                ,create_time as createTime
                ,pay_time as payTime
                ,status";
        $info = $this->CI->db->select($column)->order_by('id', 'DESC')->get_where('user_order', array('user_id' => $userId,
            'release_id'=>$releaseId,'status'=>1,'pay_type'=>1), 1, 0);
        return $info->row();
    }


    /**
     * [支付回调]
     * @param  [type] $dbmanage [description]
     * @param  [type] $userid   [description]
     * @param  [type] $weixin   [description]
     * @return [type]           [description]
     */
    public function notifyOrder(){  
        $this->CI->load->library('Wxpay/callback'); //公共 
        $retWx = $this->CI->callback->Handle();
        // $retWx = 1;
        log_message('info', 'notifyOrder,retWx:'.json_encode($retWx)); 
        if($retWx){
            $notifydata = $this->CI->callback->getDataArr(); 
            // $notifydata['out_trade_no'] = "100001315420153187535";
            log_message('info', 'notifyOrder,notifydata:'.json_encode($notifydata)); 
            $orderNumber = $notifydata['out_trade_no'];
            //1查询订单
            $orderOb = $this->CI->db->select('id,status,release_id,user_id,order_amount')->get_where('user_order', array('order_number' => $orderNumber), 1, 0);
            $orderinfo = $orderOb->row();
            log_message('info', 'notifyOrder,orderinfo:'.json_encode($orderinfo)); 
            if(isset($orderinfo->id) ) {
                $status = $orderinfo->status;
                if ($status == 1) {//支付成功了
                    $ret['status'] = 0;
                    $ret['out_data']['wxsp'] = json_encode($notifydata);
                    return $ret;
                }

                //2业务上确认一个订单 
                $ret['status'] = $this->confirmBillOrder($orderNumber,$orderinfo,$notifydata);
                log_message('info', 'notifyOrder,ret:'.json_encode($ret)); 

                $ret['out_data']['wxsp'] = json_encode($notifydata);
                return $ret;
            }
            else{
                $ret['status'] = 2001;
            }
        }
        else{
           $ret['status'] = 2024;
           $notifydata = array();
        }
        $ret['out_data']['wxsp'] = json_encode($notifydata);
        return $ret;
    } 

    /**
     * [退款支付回调，暂时不需要]
     * @param  [type] $dbmanage [description]
     * @param  [type] $userid   [description]
     * @param  [type] $weixin   [description]
     * @return [type]           [description]
     */
    public function notifyRefundOrder(){  
        // $this->CI->load->library('Wxpay/callback'); //公共 
        // $retWx = $this->CI->callback->Handle();
        // // $retWx = 1;
        // log_message('info', 'notifyOrder,retWx:'.json_encode($retWx)); 
        // if($retWx){
        //     $notifydata = $weixinob->getDataArr(); 
        //     // $notifydata['out_trade_no'] = "100001315420153187535";
        //     log_message('info', 'notifyOrder,notifydata:'.json_encode($notifydata)); 
        //     $orderNumber = $notifydata['out_trade_no'];
        //     //1查询订单
        //     $orderOb = $this->CI->db->select('id,status,release_id,user_id,order_amount')->get_where('user_order', array('order_number' => $orderNumber), 1, 0);
        //     $orderinfo = $orderOb->row();
        //     log_message('info', 'notifyOrder,orderinfo:'.json_encode($orderinfo)); 
        //     if(isset($orderinfo->id) ) {
        //         $status = $orderinfo->status;
        //         if ($status == 1) {//支付成功了
        //             $ret['status'] = 0;
        //             $ret['out_data']['wxsp'] = json_encode($notifydata);
        //             return $ret;
        //         }

        //         //2业务上确认一个订单 
        //         $ret['status'] = $this->confirmBillOrder($orderNumber,$orderinfo,$notifydata);
        //         log_message('info', 'notifyOrder,ret:'.json_encode($ret)); 

        //         $ret['out_data']['wxsp'] = json_encode($notifydata);
        //         return $ret;
        //     }
        //     else{
        //         $ret['status'] = 2001;
        //     }
        // }
        // else{
        //    $ret['status'] = 2016;
        // }
        // $ret['out_data']['wxsp'] = json_encode($notifydata);
        // return $ret;
    }

    /**
     * [confirmBillOrder description]
     * @return [type] [description]
     */
    private function confirmBillOrder($orderNumber,$orderinfo,$notifydata){
        log_message('info', "order/notifyOrder,orderNumber:$orderNumber,orderinfo:".json_encode($orderinfo).",notifydata:".json_encode($notifydata)); 
        $this->CI->db->trans_start();
        //1修改订单状态
        $status = $this->CI->db->set("status",1)->set("result",json_encode($notifydata))
            ->where("order_number",$orderNumber)->update('user_order');
        if(!$status){
            $this->CI->db->trans_rollback();
            return -1;
        }
        
        //2修改任务
        $status = $this->CI->db->set("status",1)->where("id",$orderinfo->release_id)->update('task');
        if(!$status){
            $this->CI->db->trans_rollback();
            return -2;
        }

        $this->CI->load->model("userModel");
        $extraInfo = $this->CI->userModel->extraInfo($orderinfo->user_id);
        if(isset($extraInfo->id)){
            $student_award = $this->CI->config->item('studentAward');
        }
        else{
            $student_award = 0;
        }
        //3添加记录
        $temp = array(
            "user_id"=>$orderinfo->user_id,
            "task_id"=>$orderinfo->release_id,
            "deposit"=>$orderinfo->order_amount,
            "student_award"=>$student_award,
            "left_deposit"=>$orderinfo->order_amount,
            "create_time"=>date("Y-m-d H:i:s")
        );
        $status = $this->CI->db->insert('task_obtain', $temp);
        if(!$status){
            $this->CI->db->trans_rollback();
            return -3;
        }
        $new_id = $this->CI->db->insert_id();
        //4添加日志
        $temp = array(
            "task_obtain_id"=>$new_id,
            "instruction"=>"领取任务",
        );
        $status = $this->CI->db->insert('task_obtain_log', $temp);  
        if(!$status){
            $this->CI->db->trans_rollback();
            return -4;
        }       


        $this->CI->db->trans_complete();
        return 0;
    }
    

    /**
     * [confirmRefundOrder description]
     * @return [type] [description]
     */
    public function confirmRefundOrder($orderNumber,$notifydata){
        log_message('info', "order/confirmRefundOrder,orderNumber:$orderNumber,notifydata:".json_encode($notifydata)); 
        $this->CI->db->trans_start();
        //1修改订单状态
        $status = $this->CI->db->set("status",1)->set("result",json_encode($notifydata))
            ->where("order_number",$orderNumber)->update('user_reward_order');
        if(!$status){
            $this->CI->db->trans_rollback();
            return -1;
        }       
       
        // //3添加日志
        // $temp = array(
        //     "task_obtain_id"=>$new_id,
        //     "instruction"=>"领取任务",
        // );
        // $status = $this->CI->db->insert('task_obtain_log', $temp);  
        // if(!$status){
        //     $this->CI->db->trans_rollback();
        //     return -4;
        // }       


        $this->CI->db->trans_complete();
        return 0;
    }

    /**
     * [refundOrderByOrderId description]
     * @return [type] [description]
     */
    public function refundOrderByOrderId($userId,$orderId,$type){
        log_message('info', "order/refundOrderByOrderId,userId:$userId,orderId:$orderId"); 
        $fileterArray['user_id'] = $userId;
        $fileterArray['release_order_id'] = $orderId;
        $fileterArray['order_type'] = $type;
         
        $totalQuery = $this->CI->db->select("id")
                ->get_where('user_reward_order', $fileterArray, 1, 0);
        $info = $totalQuery->row();
        return $info;
    }


}